#include <windows.h>
#include "MyStrPacker.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMyStrPacker::CMyStrPacker()
	:m_uBufLen(1), m_uBufSize(0), m_pBuf(NULL)
{

}

CMyStrPacker::~CMyStrPacker()
{

}

//////////////////////////////////////////////////////////////////////
BOOL CMyStrPacker::AddString(const char* pszString)
{
	if (!m_pBuf)
		return FALSE;

	if (pszString)
	{
		UINT uLen = strlen(pszString);
		if (uLen > 255)
			return FALSE;

		UINT uCurSize	=this->GetSize();
		if (m_uBufSize < 1 + uLen + uCurSize)
			return FALSE;
		
		UCHAR* pBuf	= (UCHAR*)m_pBuf;
		*pBuf = (UCHAR)(this->GetStrAmount() + 1);

		pBuf	+=uCurSize;
		*pBuf	=static_cast<unsigned char>(uLen);
		pBuf++;
		memcpy(pBuf, pszString, uLen);

		m_uBufLen += uLen+1;
	}
	else
	{
		UINT uSize	=this->GetSize();

		UCHAR* pBuf	=(UCHAR*)m_pBuf;
		*pBuf	=(UCHAR)(this->GetStrAmount()+1);

		pBuf	+=uSize;
		*pBuf	=0;

		m_uBufLen += 1;
	}

	return TRUE;
}

//////////////////////////////////////////////////////////////////////
void CMyStrPacker::SetBuf(char *pBuf, UINT uBufSize)
{
	m_pBuf		=pBuf;
	m_uBufSize	=uBufSize;
	m_uBufLen	=1;

	memset(m_pBuf, 0L, m_uBufSize);
}

//////////////////////////////////////////////////////////////////////
void CMyStrPacker::Clear()
{
	memset(m_pBuf, 0, m_uBufSize);
	m_uBufLen	=1;
}

//////////////////////////////////////////////////////////////////////
CMyString CMyStrPacker::GetString(UINT uIndex) const
{
	UCHAR*	pBuf	=(UCHAR*)m_pBuf;
	pBuf++;

	UINT uAmount	=this->GetStrAmount();
	if (uIndex >= uAmount)
		return "";

	CMyString str;
	for (UINT i=0; i<uAmount; i++)
	{
		UCHAR ucStrSize	= *pBuf;

		if(uIndex == i)	// got it...
		{
			for (int j=0; j<(int)ucStrSize; j++)
				str += pBuf[1+j];

			return str;
		}
		else			// next string
			pBuf += (1+ucStrSize);
	}

	return "";
}

//////////////////////////////////////////////////////////////////////
BOOL CMyStrPacker::GetString(UINT uIndex, char* pszStrBuf, UINT uBufSize) const
{
	memset(pszStrBuf, 0L, uBufSize);

	UCHAR*	pBuf	=(UCHAR*)m_pBuf;
	pBuf++;

	UINT uAmount	=this->GetStrAmount();
	if(uIndex >= uAmount)
		return FALSE;

	for(UINT i=0; i<uAmount; i++)
	{
		UCHAR ucStrSize	=*pBuf;	// get size...

		if(uIndex == i)	// got it...
		{
			if(uBufSize <= (UINT)ucStrSize)
				return FALSE;
			else
			{
				memcpy(pszStrBuf, pBuf+1, (int)ucStrSize);
				return TRUE;
			}
		}
		else			// next string
			pBuf	+=(1+ucStrSize);
	}

	return FALSE;
}

//////////////////////////////////////////////////////////////////////
UINT CMyStrPacker::GetStrAmount(void) const
{
	UCHAR*	pBuf	=(UCHAR*)m_pBuf;
	return *pBuf;
}
